package com.inifitness.common.event.aspect;

import jakarta.annotation.Resource;

import com.inifitness.common.annotations.PublishEvent;
import com.inifitness.common.event.event.MessageEvent;
import com.inifitness.common.rabbitmq.EventRabbitConfig;

import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * TODO: (sunjinfeng 2024-05-27)
 *
 * @author sunjinfeng
 * @version 1.0.0
 * @since 2024-05-27 13:15
 */
@Aspect
@Component
@Log4j2
public class EventPublisherAspect {

  @Resource
  private RabbitTemplate rabbitTemplate;

  @AfterReturning(pointcut = "@annotation(publishEvent)", returning = "result")
  public void doAfterReturning(final JoinPoint joinPoint, PublishEvent publishEvent,
      Object result) {
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = joinPoint.getSignature().getName();
    log.debug("class={},method={}",className,methodName);
    MessageEvent event = new MessageEvent(publishEvent.eventCode(), result);
    rabbitTemplate.convertAndSend(EventRabbitConfig.EVENT_EXCHANGE, EventRabbitConfig.EVENT_ROUTING,
        event);
    log.info("推送事件到RabbitMQ,推送方式:触发, 消息:{}", event);
  }
}
